/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { TablePaginationConfig } from 'antd';
import { isFunction } from 'lodash';
import { useState } from 'react';
import { Location, useLocation } from 'umi';

if (typeof window !== 'undefined') {
  window.cacheMap = window.cacheMap || {};
}

/**
 *
 * @description 缓存id
 * @param id
 * @returns
 */
export function useCacheId(id: string): {
  cacheId: string;
  getCache: () => any;
  setCache: (p: any) => void;
} {
  const location: Location = useLocation();
  const { pathname } = location;
  const cacheId = `${pathname}-${id}`;
  const cacheMap = window.cacheMap;
  return {
    cacheId,
    getCache: () => cacheMap[cacheId],
    setCache: (p: any) => {
      cacheMap[cacheId] = p;
    },
  };
}

/**
 *
 * @description 缓存翻页
 * @param id
 * @returns
 */
export function usePaginationCache(
  id: string,
  opts?: TablePaginationConfig,
): TablePaginationConfig {
  const { getCache, setCache } = useCacheId(id);
  const { onChange } = opts || {};
  const [pagination, setPagination] = useState({
    ...opts,
    ...getCache(),
  });
  return {
    ...pagination,
    onChange: (page, pageSize) => {
      setCache({
        current: page,
        pageSize,
      });
      setPagination(getCache());
      if (isFunction(onChange)) {
        onChange(page, pageSize);
      }
    },
  };
}
